﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using TileMapEditor.Config;

namespace TileMapEditor.IO
{
    public static class TileMapEditorIO
    {
        private static Vector2 pos;

        public static void Save( string filename, Dictionary<Vector2, int> dict, Vector2 size )
        {
            int row = (int) size.x;
            int col = (int) size.y;

            using ( var bw = new BinaryWriter( File.Open( filename, FileMode.Create ) ) )
            {
                for ( int i = 0; i < size.x; i++ )
                {
                    for ( int j = 0; j < size.y; j++ )
                    {
                        pos.x = i; pos.y = j;

                        if ( dict.ContainsKey( pos ) )
                        {
                            bw.Write( dict[pos] );
                        }
                        else
                        {
                            bw.Write( TileMapSettings.areaType[TileMapIds.blocked] );
                        }
                    }
                }
            }
        }

        public static void Load( string filename, Vector2 size, ref Dictionary<Vector2, int> dict )
        {
            //Debug.Log( size.ToString() );

            if ( string.IsNullOrEmpty( filename ) || ! File.Exists( filename ) )
            {
                //Debug.Log( "File " + filename + " not exists." );
                return;
            }

            if ( null == dict )
                dict = new Dictionary<Vector2, int>();

            int row = (int) size.x;
            int col = (int) size.y;

            using ( var br = new BinaryReader( File.Open( filename, FileMode.Open ) ) )
            {
                dict = new Dictionary<Vector2, int>();

                for ( int i = 0; i < size.x;  i++ )
                {
                    for ( int j = 0; j < size.y;  j++ )
                    {
                        var curpos = new Vector2( i, j );
                        var val = br.ReadInt32();

                        if ( val != TileMapSettings.areaType[TileMapIds.blocked] )
                            dict.Add( curpos, val );
                    }
                }
            }
        }
    }
}
